<?php
    require_once('../config/config.php');

    function louer_film($client_id, $film_id, $date){
        //TODO Check if #client.films < 3
        //TODO Check date fomat like  '2012-02-16 20:42:00'

        // Insert location
        $sql = "INSERT INTO locations (loc_film, loc_cli, loc_deb, loc_fin)
                VALUES ($film_id, $client_id, '$date', null)";
        execQuery($sql);
    }

    //TODO function retirer_film($client_id, $film_id);
    // Une fois le film réservé il faut le retirer

    function retourner_film($client_id, $film_id, $date_deb, $date_fin){
        //TODO Check if (client, film) exists in locations
        
        $cout = calcul_cout($client_id, $film_id, $date_deb, $date_fin);

        // Insert return date
        $sql = "update locations
                set loc_fin = '$date_fin',
                    loc_montant = $cout
                where loc_film = $film_id
                and loc_cli = $client_id
                and loc_deb = '$date_deb'";
        execQuery($sql);
    }

    // Calcul du cout de la location lors du retour du DVD
    function calcul_cout($client_id, $film_id, $date_deb, $date_fin){
        
        $dt_deb = new DateTime($date_deb);
        $dt_fin = new DateTime($date_fin);
        $diff = $dt_deb->diff($dt_fin);
        $D = $diff->format('%d');
        $H = $diff->format('%H');
        $M = $diff->format('%I');
        $S = $diff->format('%S');

        $cout = 2; // Droit de gestion : 1€ + 12 1eres heures : 1€
        if($D >= 1){
            $cout = 50;
        } else {

            // Vérifier cas location gratuite (toutes les 15 loc)
            $nbLoc = getNbLocations($client_id);
            if($nbLoc != 0){
                $nbLoc -= 15;
                if($nbLoc == 0 || $nbLoc%16 == 0){
                    return 0;
                }   
            }
            
            // 0.5€/h entre 12h et 24h
            if ($H >= 12){ 
                $HSup = $H-12;
                $cout += $HSup * 0.5;
            }
        }

        return $cout;

        /*$deb = $dt_deb->format('Y-m-d H:i:s');
        $fin = $dt_fin->format('Y-m-d H:i:s');
        echo "$deb - $fin - $D"."j $H:$M:$S - $cout €<br>";*/
    }

    function getNbLocations($client_id){
        $sql = "select count(*) from locations
                where loc_cli = $client_id
                and loc_fin is not null";

        $rq = execQuery($sql);
        $res = $rq->fetch(PDO::FETCH_ASSOC);
        return $res["count"];
    }

?>
